package rocketmq.demo2.order.message;

import java.util.Date;
import java.util.List;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.MessageQueueSelector;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.common.message.MessageQueue;
import com.alibaba.rocketmq.remoting.common.RemotingHelper;

public class OrderedProducer {
	public static void main(String[] args) throws Exception {
		DefaultMQProducer producer = new DefaultMQProducer("orderGroup");
		// 指定nameServer的地址 （测试时在代码中指定）
		producer.setNamesrvAddr("127.0.0.1:9876");
		producer.start();
		// String[] tags = new String[] { "TagA", "TagB", "TagC", "TagD", "TagE"
		// };
		for (int i = 0; i < 10; i++) {
			int orderId = i % 10;
			String content = "你好  RocketMQ, " + new Date().getTime() + "-->" + i;
			Message msg = new Message("Topic_Order", "TagA", "KEY" + i,
					content.getBytes(RemotingHelper.DEFAULT_CHARSET));
			
			SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
				@Override
				public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
					Integer id = (Integer) arg;
					int index = id % mqs.size();
					return mqs.get(index);
				}
			}, orderId);

			System.out.printf("%s%n", sendResult);
		}
		// server shutdown
		producer.shutdown();
	}
}
